/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.restful.config.msgback;

import com.robam.cloud.common.bean.restful.entity.RespMsg;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Description 异常处理的全局配置
 * @Author 薛铁琪
 * @CreateTime 2018-12-18 23:42
 * @Version 1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 已知异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public RespMsg handleBaseException(ServiceException ex) {
        RespMsg respMsg;
        log.error("ServiceException {}", ex.getMsg());
        respMsg = RespMsg.error(ex.getCode(), ex.getMessage());
        return respMsg;
    }

    /**
     * 未知异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RespMsg handleException(Exception ex) {
        RespMsg response;
        log.error("Exception error:{}", ex);
        //参数错误
        if (ex instanceof MethodArgumentNotValidException) {
            BindingResult result = ((MethodArgumentNotValidException) ex).getBindingResult();
            response = RespMsg.error(RespMsg.RESULT_CODE_400, wrapperError(result));
            return response;
        }
        response = RespMsg.error(RespMsg.RESULT_CODE_500, ex.getMessage());
        return response;
    }

    private String wrapperError(BindingResult result) {
        List<ObjectError> list = result.getAllErrors();
        String eMsg = "";
        if (list.size() > 0) {
            eMsg = list.get(0).getDefaultMessage();
        }
        return eMsg;
    }
}
